<template>
  <div class="app-container">
    <el-form :model="operationForm" :rules="rules" ref="operationForm" label-width="auto" class="scheme-addForm">
      <div style="text-align: right">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="onCancel">取消</el-button>
      </div>
<!--      <el-card class="box-card" style="margin-top: 20px">-->
<!--        <div slot="header" class="clearfix">-->
<!--          <span>基本信息</span>-->
<!--        </div>-->
<!--        <el-row :gutter="20">-->
<!--          <el-col :md="8" :xs="11">-->
<!--            <el-form-item label="单据编号" prop="orderCode">-->
<!--              <el-input v-model="operationForm.orderCode" placeholder="YZOYW+数字/字母" :disabled="true"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :md="8" :xs="11">-->
<!--            <el-form-item label="业务填报" prop="businessFillingName">-->
<!--              <el-input v-model="operationForm.businessFillingName" :disabled="true"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :md="8" :xs="11">-->
<!--            <el-form-item label="填写日期" prop="fillingTime">-->
<!--              <el-date-picker type="datetime" placeholder="选择日期" :disabled="true" v-model="operationForm.fillingTime" style="width: 100%;"></el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :md="8" :xs="11">-->
<!--            <el-form-item label="所在部门" prop="deptName">-->
<!--              <el-input v-model="operationForm.deptId" :disabled="true" v-show="false"></el-input>-->
<!--              <el-input v-model="operationForm.deptName" :disabled="true"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          &lt;!&ndash;          <el-col :md="8" :xs="11">&ndash;&gt;-->
<!--          &lt;!&ndash;            <el-form-item label="所在岗位" prop="postId">&ndash;&gt;-->
<!--          &lt;!&ndash;              <el-select v-model="operationForm.postId" style="width: 100%" placeholder="请选择岗位" clearable>&ndash;&gt;-->
<!--          &lt;!&ndash;                <el-option&ndash;&gt;-->
<!--          &lt;!&ndash;                  v-for="option in postsData"&ndash;&gt;-->
<!--          &lt;!&ndash;                  :key="option.postId"&ndash;&gt;-->
<!--          &lt;!&ndash;                  :label="option.postName"&ndash;&gt;-->
<!--          &lt;!&ndash;                  :value="option.postId"&ndash;&gt;-->
<!--          &lt;!&ndash;                />&ndash;&gt;-->
<!--          &lt;!&ndash;              </el-select>&ndash;&gt;-->
<!--          &lt;!&ndash;            </el-form-item>&ndash;&gt;-->
<!--          &lt;!&ndash;          </el-col>&ndash;&gt;-->

<!--          <el-col :md="8" :xs="11">-->
<!--            <el-form-item label="备注" prop="remark">-->
<!--              <el-input type="textarea" style="width: 100%" v-model="operationForm.remark" :min="0"></el-input>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--      </el-card>-->

      <el-card class="mt20 box-card">
        <div slot="header" class="clearfix">
          <span>用工需求预测</span>
        </div>
        <el-row :gutter="20">
          <el-col :md="8" :xs="11">
            <el-form-item label="单据编号" prop="orderCode">
              <el-input v-model="operationForm.orderCode" placeholder="YZOYW+数字/字母" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11" v-show="false">
            <el-form-item label="业务填报" prop="businessFillingName">
              <el-input v-model="operationForm.businessFillingName" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
<!--          <el-col :md="8" :xs="11">-->
<!--            <el-form-item label="填写日期" prop="fillingTime">-->
<!--              <el-date-picker type="datetime" placeholder="选择日期" :disabled="true" v-model="operationForm.fillingTime" style="width: 100%;"></el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :md="8" :xs="11" v-show="false">
            <el-form-item label="所在部门" prop="deptName">
              <el-input v-model="operationForm.deptId" :disabled="true" v-show="false"></el-input>
              <el-input v-model="operationForm.deptName" :disabled="true"></el-input>
            </el-form-item>
          </el-col>

          <el-col :md="8" :xs="11">
            <el-form-item label="用工日期" prop="workTime">
              <el-date-picker type="date" format="yyyy-MM-dd" placeholder="选择日期" @change="getStrategyValue" :picker-options="pickerOptions" v-model="operationForm.workTime" style="width: 100%;"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="班组" prop="workGroupId">
              <el-select v-model="operationForm.workGroupId" style="width: 100%" placeholder="请选择班组" clearable>
                <el-option
                  v-for="option in depsData"
                  :key="option.workGroupId"
                  :label="option.workGroupName"
                  :value="option.workGroupId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="班次" prop="timeShiftId">
              <el-select v-model="operationForm.timeShiftId" @change="getStrategyValue" style="width: 100%" placeholder="请选择班次" clearable>
                <el-option
                  v-for="option in timeShift"
                  :key="option.timeShiftId"
                  :label="option.timeShiftName"
                  :value="option.timeShiftId"
                />
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :md="8" :xs="11">-->
<!--            <el-form-item label="预估业务量" prop="predictNumber">-->
<!--              <template v-if="strategyYw">-->
<!--                <el-input style="width: 100%" v-model="operationForm.predictNumber" placeholder="请选择班次用工时间" :min="0" :disabled="strategyYw"></el-input>-->
<!--              </template>-->
<!--              <template v-else>-->
<!--                <el-input-number style="width: 100%" @change="getStrategyValue" v-model="operationForm.predictNumber" :min="0" :disabled="strategyYw"></el-input-number>-->
<!--              </template>-->

<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :md="8" :xs="11">
            <el-form-item label="班组遗留" prop="bequeath">
              <el-input type="number" min="0" @change="getPredictNumber" v-model="operationForm.bequeath">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="预测24h" prop="future24PredictNumber">
              <el-input v-model="operationForm.future24PredictNumber" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="预测12h" prop="future12PredictNumber">
              <el-input v-model="operationForm.future12PredictNumber" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="省内未发" prop="provinceNotIssued">
              <el-input v-model="operationForm.provinceNotIssued" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="车辆数" prop="carNumber">
              <el-input v-model="operationForm.carNumber" :disabled="true">
                <template slot="append">辆</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="待卸量" prop="unloadedNumber">
              <el-input v-model="operationForm.unloadedNumber" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="预测总量" prop="predictNumber">
              <el-input v-model="operationForm.predictNumber" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>


          <el-col :md="8" :xs="11">
            <el-form-item label="启用方案" prop="enableSchemeId">
              <template v-if="strategyFa">
                <!--                <el-input v-model="operationForm.enableSchemeId" :disabled="true"></el-input>-->
                <el-input v-model="operationForm.enableSchemeName" :disabled="true"></el-input>
              </template>
              <template v-else>
                <el-select v-model="operationForm.enableSchemeId" style="width: 100%" placeholder="请选择方案" @change="handleSchemeChange" clearable>
                  <el-option
                    v-for="option in schemeData"
                    :key="option.id"
                    :label="option.programmeName"
                    :value="option.id"
                  />
                </el-select>
              </template>

            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="业务量分档" prop="businessClassification">
<!--              <el-input-number style="width: 100%" v-model="operationForm.businessClassification" :min="0" :disabled="true"></el-input-number>-->
              <el-input v-model="operationForm.businessClassification" :disabled="true">
                <template slot="append">万件</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="标准人数" prop="standardNumber">
              <el-input-number style="width: 100%" v-model="operationForm.standardNumber" :min="0" :disabled="true"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="预估用工量" prop="estimatedLaborNum">
              <el-input-number style="width: 100%" v-model="operationForm.estimatedLaborNum" :min="0" :disabled="true"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="标准人效比" prop="standardRatio">
              <el-input style="width: 100%" v-model="operationForm.standardRatio" :min="0" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="预估人效比" prop="estimateRatio">
              <el-input style="width: 100%" v-model="operationForm.estimateRatio" :min="0" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="控制百分比" prop="controlRatio">
              <el-input style="width: 100%" v-model="operationForm.controlRatio" :min="0" :disabled="true">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :md="8" :xs="11">
            <el-form-item label="预估百分比" prop="estimatedArrivalRatio">
              <el-input style="width: 100%" v-model="operationForm.estimatedArrivalRatio" :min="0" :disabled="true">
                <template slot="append">%</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :md="8" :xs="11">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" autosize style="width: 100%" v-model="operationForm.remark" :min="0"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="mt20 box-card">
        <div slot="header" class="clearfix">
          <span>人员配置</span>
        </div>
        <el-table
          :data="staffData"
          :span-method="objectSpanMethod"
          border
          size="mini"
          show-summary
          :summary-method="getSummaries"
          style="width: 100%">
          <el-table-column
            prop="regionName"
            label="区域"></el-table-column>
          <el-table-column
            prop="groupName"
            label="组别">
          </el-table-column>
          <el-table-column
            prop="groupNumber"
            align="center"
            label="组别人数">
<!--            <template slot-scope="scope">-->
<!--              <el-input-number size="mini" v-model="scope.row.groupNumber" style="width: 100%" :min="0" :disabled="true"></el-input-number>-->
<!--            </template>-->
          </el-table-column>
          <el-table-column
            prop="postName"
            label="岗位">
          </el-table-column>
          <el-table-column
            prop="quota"
            align="center"
            label="定额">
            <template slot-scope="scope">
              <span>{{scope.row.quota}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="regionNumber"
            min-width="120px"
            label="区域人数">
            <template slot-scope="scope">
              <el-input-number size="mini" controls-position="right" v-model="scope.row.regionNumber" @change="(e)=>handleChange(e,scope.row)" style="width: 100%" :min="0"></el-input-number>
            </template>
          </el-table-column>
        </el-table>

        <el-alert
          v-if="warning"
          :title="'汇总人数超过预估人数的'+warningRate+'%！'"
          :closable="false"
          show-icon
          type="warning">
        </el-alert>

      </el-card>

      <el-card class="mt20 box-card">
        <div slot="header" class="clearfix">
          <span>附件</span>
        </div>
        <div style="max-width: 500px">
          <el-upload
            :limit="2"
            class="upload-annex"
            :headers="upload.headers"
            :action="upload.url"
            :on-preview="handleUploadPreview"
            :on-change="handleUploadChange"
            :on-remove="handleUploadRemove"
            :on-exceed="handleUploadExceed"
            :file-list="fileList">
            <el-button size="small" type="primary">上传文件</el-button>
            <div slot="tip" class="el-upload__tip">最多上传两个附件</div>
            <!--            <div slot="tip" class="el-upload__tip">支持扩展名：.rar .zip .doc .docx .pdf .jpg</div>-->
          </el-upload>
        </div>

      </el-card>
    </el-form>

    <!-- 修改设备状态对话框 -->
    <el-dialog :title="title" :visible.sync="statusOpen" width="500px" append-to-body>
      <el-form ref="statusForm" :model="statusForm" :rules="statusRules" label-width="80px">
        <el-form-item label="设备">
          <span style="padding: 10px">{{statusData.row.equipmentName}} {{statusData.column.property}}点 作业状态</span>
        </el-form-item>

        <el-form-item label="作业状态" prop="status">
          <el-select v-model="statusForm.status" placeholder="请选择状态">
            <el-option label="启用" :value="1"></el-option>
            <el-option label="停用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStatusForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
  import { getSchemeList, getSchemeDetail, getTimeShiftAndDep } from "@/api/job/scheme";
  import { getStrategyValue, getSchemeConfigAndStrategy, updateOperationalInfo, getOperationalDetail } from "@/api/operation";
  import {parseTime} from "@/utils/ruoyi";
  import {getToken} from "@/utils/auth";

  export default {
    data(){
      return {
        //禁用时间
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
        upload:{
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/common/upload"
        },
        //预估业务量策略
        strategyYw: false,
        //启用方案策略
        strategyFa: false,
        strategyFaData:{},
        //预警额度
        warningRate: '',
        //汇总人数超出预警
        warning: false,
        //班次
        timeShift: [],
        //班组
        depsData: [],
        //岗位
        postsData: [],
        //附件文件列表
        fileList: [],
        //方案列表
        schemeData: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //设备状态弹出层
        statusOpen: false,
        statusData: { row: {}, column: {}},
        areaOptions: [],
        //设备工作时间
        deviceTime: [],
        deviceData: [],
        allAreaData: [],  //全部区域数据
        equipments: [],  //设备列表
        baseData: {},  //订单基础数据
        staffData: [],
        statusForm: {
          status: ''
        },
        deviceForm: {
          date1: '',
          date2: '',
        },
        operationForm: {
          orderCode: '',
          businessFillingName: '',
          deptName: '',
          remark: '',
          workTime: new Date().getTime()+24*60*60*1000,
          // fillingTime: new Date().getTime(),
          workGroupId: '',
          timeShiftId: '',
          predictNumber:undefined,//预估业务量
          enableSchemeId: '', //启用方案
          estimatedLaborNum: '', //预估用工量
        },
        addForm: {
          area: '',
        },
        statusRules: {
          status: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
        },
        deviceRules: {
          date1: [
            { required: true, message: '请选择时间', trigger: 'change' }
          ],
          date2: [
            { required: true, message: '请选择时间', trigger: 'change' }
          ],
        },
        addRules: {
          area: [
            { required: true, message: '请选择区域', trigger: 'change' }
          ],
        },
        rules: {
          orderCode: [
            { required: true, message: '请输入单据编号', trigger: 'blur' },
            { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          remark: [
            { required: false, message: '请输入备注', trigger: 'blur' },
            { min: 0, max: 200, message: '长度在 0 到 200 个字符', trigger: 'blur' }
          ],
          // fillingTime: [
          //   { required: true, message: '请输入填写日期', trigger: 'change' },
          // ],
          workTime: [
            { required: true, message: '请输入用工时间', trigger: 'change' },
          ],
          workGroupId: [
            { required: true, message: '请选择班组', trigger: 'change' },
          ],
          timeShiftId: [
            { required: true, message: '请选择班次', trigger: 'change' },
          ],
          predictNumber: [
            { required: true, message: '请填写班组遗留', trigger: 'change' }
          ],
          bequeath: [
            { required: true, message: '请填写班组遗留', trigger: 'change' }
          ],
          businessClassification: [
            { required: true, message: '请选择业务量分档', trigger: 'change' }
          ],
          standardNumber: [
            { required: true, message: '请输入标准人数', trigger: 'blur' },
          ],
          estimatedLaborNum: [
            { required: true, message: '请输入预估用工量', trigger: 'blur' },
          ],
          enableSchemeId: [
            { required: true, message: '请选择启用方案', trigger: 'change' },
          ],
        }
      }
    },
    created(){
      const params = this.$route.query;
      if(params){
        this.getOperationalDetail(params)
      }

      //获取基础信息
      this.getTimeShiftAndDep();
    },
    mounted(){
    },
    computed: {
      areaNum(){  //获取区域数组
        return new Set(this.staffData.map(o => o.regionName));
      },
      groupNum(){  //获取组别数组
        return new Set(this.staffData.map(o => o.groupName));
      },

    },
    methods:{
      //获取详情信息
      getOperationalDetail(params){
        getOperationalDetail(params).then(res => {
          console.log(res)
          if(res.code === 200){
            const data = res.data || {};
            const baseData = data.baseData || {};
            this.baseData = baseData;
            //详情数值回填
            this.operationForm = {
              ...this.operationForm,
              orderCode: baseData.orderCode,
              // fillingTime: baseData.fillingTime,
              businessFillingName: baseData.businessFillingName,
              deptId: baseData.deptId,
              deptName: baseData.deptName,
              remark: baseData.remark,
              workTime: baseData.workTime,
              timeShiftId: baseData.shiftTimeId,
              predictNumber: baseData.predictNumber,
              workGroupId: baseData.workGroupId,
              enableSchemeId: baseData.enableSchemeId,
              enableSchemeName: baseData.enableSchemeName,
              businessClassification: baseData.businessClassification,
              standardNumber: baseData.standardNumber,
              estimatedLaborNum: baseData.estimatedLaborNum,
              standardRatio: baseData.standardRatio,
              estimateRatio: baseData.estimateRatio,
              // controlRatio: baseData.controlRatio,
              estimatedArrivalRatio: baseData.estimatedArrivalRatio,
              //预测数据
              bequeath: baseData.bequeath,
              carNumber: baseData.carNumber,
              future12PredictNumber: baseData.future12PredictNumber,
              future24PredictNumber: baseData.future24PredictNumber,
              provinceNotIssued: baseData.provinceNotIssued,
              unloadedNumber: baseData.unloadedNumber,
            }
            //根据方案id 人员配置以及超限策略获取
            this.getSchemeConfigAndStrategy(baseData.enableSchemeId,false)
            this.staffData = data.deps;
            const fileList = [];
            const urls = data.urls || [];
            urls.forEach((item,index)=>{
              const num = index+1;
              // const name = item.substring(item.lastIndexOf("/")+1);
              const obj = {
                name: "附件"+num,
                fileName: item,
                url: item
              };
              fileList.push(obj)
            })
            this.fileList = fileList;
          }
        })
      },
      warningStatus(){  //汇总人数预警
        const quota = this.getQuotaSum();
        const total = this.getAreaSum();
        // console.log(quota,total)
        const rate = (total-quota)/quota*100;
        if(this.warningRate && quota && total && rate > this.warningRate){
          this.warning = true
        }else {
          this.warning = false
        }

        // const warningRate = this.warningRate;
        // if(warningRate){
        //   //合理人数
        //   const form = this.operationForm;
        //   const rational = (form.standardNumber / form.businessClassification)*form.predictNumber*(1+warningRate/100);
        //   // const quota = this.getQuotaSum();
        //   const total = this.getAreaSum();
        //   // console.log(quota,total)
        //   const rate = (total-rational)/rational*100;
        //   if( rational && total && rate >= warningRate){
        //     this.warning = true
        //   }else {
        //     this.warning = false
        //   }
        // }else {
        //   this.warning = false
        // }

      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.statusOpen = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          area: undefined,
        };
        this.resetForm("addForm");
        this.resetForm("statusForm");
      },
      //文件上传长度限制
      handleUploadExceed(file,fileList){
        this.msgError(`最多上传 ${fileList.length} 个附件`)
      },
      //文件删除
      handleUploadRemove(file,fileList){
        this.fileList = fileList;
        // console.log(file,fileList)
      },
      //文件状态改变时
      handleUploadChange(file, fileList){
        console.log(file,fileList)
        if(file.status === 'success'){
          const res = file.response;
          if(res.code && res.code === 200){
            this.fileList = fileList;
          }else {
            this.fileList = fileList.filter(item => item.uid !== file.uid);
            this.msgError(res.msg || '文件上传失败')
          }
        }
        // console.log(file, fileList)
      },
      handleUploadPreview(file){
        console.log(file)
        if(file.status === 'success'){
          const res = file.response || {};
          if(file.fileName){
            window.location.href = process.env.VUE_APP_BASE_API + "/common/download/resource?resource=" + encodeURI(file.fileName) + "&delete=" + false;
          }else if(res.code && res.code === 200){
            window.location.href = process.env.VUE_APP_BASE_API + "/common/download/resource?resource=" + encodeURI(res.fileName) + "&delete=" + false;
          }
        }
      },
      //方案下拉改变
      handleSchemeChange(value){
        // console.log(value);
        if(!value){
          this.operationForm = {
            ...this.operationForm,
            enableSchemeName: null,
            businessClassification: null,
            standardNumber: null,
            standardRatio: null,
            estimatedArrivalRatio: null,
          }
          return false
        }
        this.schemeData.forEach(item =>{
          if(item.id === value){
            const standardRatio = (item.businessClassification*10000)/item.standardNumber*100;
            this.operationForm = {
              ...this.operationForm,
              enableSchemeName: item.programmeName,
              businessClassification: item.businessClassification,
              standardNumber: item.standardNumber,
              standardRatio: standardRatio.toFixed(2),
              estimateRatio: null,
              estimatedArrivalRatio: null,
            }
          }
        })
        this.getSchemeConfigAndStrategy(value)

      },
      //获取配置信息
      getTimeShiftAndDep(){
        getTimeShiftAndDep().then(res => {
          // console.log(res);
          const data = res.data || {};
          this.depsData = data.deps;
          this.postsData = data.posts;
          this.timeShift = data.timeShift;
          //判断策略是否开启 （预估业务量和启用策略）
          if(data.strategyYw){
            //禁用预估业务量
            this.strategyYw = true;
          }
          if(data.strategyFa) {
            this.strategyFa = true;
          }else {
            this.schemeData = data.faResult;
          }

        })
      },
      //获取预测总量
      getPredictNumber(val){
        const bequeath = val*1;
        //获取策略信息
        this.getStrategyValue();
        const { future24PredictNumber, future12PredictNumber, provinceNotIssued, estimatedLaborNum } = this.operationForm;
        const predictNumber = future24PredictNumber - future12PredictNumber + provinceNotIssued + bequeath;
        if(!isNaN(predictNumber)){
          //预估人效比
          const estimateRatio = estimatedLaborNum ? predictNumber*10000/estimatedLaborNum : 0;

          this.operationForm = {
            ...this.operationForm,
            predictNumber: predictNumber,
            estimateRatio: estimateRatio.toFixed(2),
          }
        }

      },
      //获取策略信息
      getStrategyValue(){
        // console.log(this.operationForm.timeShift)
        const { timeShiftId, workTime, predictNumber, estimatedLaborNum, bequeath } = this.operationForm;
        console.log(bequeath);
        const hasBequeath = bequeath !== undefined && bequeath !== "";

        //预估人效比
        const estimateRatio = estimatedLaborNum ? predictNumber/estimatedLaborNum : 0;
        this.operationForm.estimateRatio = (estimateRatio*100).toFixed(2);

        //重置
        this.operationForm.predictNumber = undefined;

        // console.log(timeShiftId,workTime,this.strategyYw,this.strategyFa);
        //判断策略是否开启
        const time = parseTime(workTime,'{y}-{m}-{d}');
        if(this.strategyYw && this.strategyFa){
          if(timeShiftId && workTime && hasBequeath){
            const params = {timeShiftId,workTime:time,bequeath};
            this.getStrategyValue1(params);
          }else {
            this.operationForm = {
              ...this.operationForm,
              predictNumber: undefined,
              carNumber: undefined,
              future12PredictNumber: undefined,
              future24PredictNumber: undefined,
              provinceNotIssued: undefined,
              unloadedNumber: undefined,
              estimatedArrivalRatio:undefined,
              // bequeath: undefined,
            }
          }
        }else if(this.strategyYw){
          if(timeShiftId && workTime && hasBequeath){
            const params = {timeShiftId,workTime:time,bequeath};
            this.getStrategyValue1(params);
          }else {
            this.operationForm = {
              ...this.operationForm,
              predictNumber: undefined,
              carNumber: undefined,
              future12PredictNumber: undefined,
              future24PredictNumber: undefined,
              provinceNotIssued: undefined,
              unloadedNumber: undefined,
              estimatedArrivalRatio:undefined,
              // bequeath: undefined,
            }
          }
        }else if(this.strategyFa){
          if(timeShiftId && workTime && hasBequeath){
            const params = {timeShiftId,workTime:time,bequeath};
            this.getStrategyValue1(params);
          }
        }
      },
      //获取策略接口
      getStrategyValue1(params){
        getStrategyValue(params).then(res=>{
          // console.log(res);
          const data = res.data || {};
          if(data.code === 200){
            const strategy = data.data || {};
            //获取 订单号
            // this.operationForm = {
            //   ...this.operationForm,
            //   orderCode: strategy.orderCode,
            // }
            const dataYw = strategy.strategyYw;
            if(dataYw){
              this.operationForm = {
                ...this.operationForm,
                carNumber: dataYw.carNumber,
                predictNumber: dataYw.predictNumber.toFixed(2),
                future12PredictNumber: dataYw.future12PredictNumber,
                future24PredictNumber: dataYw.future24PredictNumber,
                provinceNotIssued: dataYw.provinceNotIssued,
                unloadedNumber: dataYw.unloadedNumber,
                estimatedArrivalRatio:undefined,
                // bequeath: undefined,
              }
            }
            // if(strategy.strategyYw && strategy.strategyYw.predictNumber){
            //   this.operationForm = {
            //     ...this.operationForm,
            //     predictNumber: strategy.strategyYw.predictNumber,
            //   }
            // }
            if(strategy.strategyFa && strategy.strategyFa.id){
              this.operationForm = {
                ...this.operationForm,
                enableSchemeName: strategy.strategyFa.programmeName,
                enableSchemeId: strategy.strategyFa.id,
                businessClassification: strategy.strategyFa.businessClassification,
                standardNumber: strategy.strategyFa.standardNumber,
                estimatedArrivalRatio:undefined,
              }
              this.strategyFaData = strategy.strategyFa;
              //根据方案id获取人员配置和超限策略
              this.getSchemeConfigAndStrategy(strategy.strategyFa.id)
            }
          }else {
            this.msgError(data.msg);
            if(this.strategyYw){
              this.operationForm = {
                ...this.operationForm,
                predictNumber: undefined,
                carNumber: undefined,
                future12PredictNumber: undefined,
                future24PredictNumber: undefined,
                provinceNotIssued: undefined,
                unloadedNumber: undefined,
                estimatedArrivalRatio:undefined,
                // bequeath: undefined,
              }
            }
            if(this.strategyFa){
              this.operationForm = {
                ...this.operationForm,
                enableSchemeName: null,
                enableSchemeId: null,
                businessClassification: null,
                standardNumber: null,
              }
            }
          }
        })
      },
      //人员配置以及超限策略获取
      getSchemeConfigAndStrategy(id,isChange = true){
        getSchemeConfigAndStrategy(id).then(res=>{
          console.log(res)
          const data = res.data || {};

          if(isChange){
            this.staffData = data.deps;
            //重置预估用工量
            this.operationForm = {
              ...this.operationForm,
              estimatedLaborNum:undefined
            }
            const deviceData = this.convertDeviceData(data.equipments)
            this.deviceData = deviceData;
          }

          //超限策略
          if(data.strategyCx){
            console.log(data.strategyCx)
            this.warningRate = data.strategyCx;
            this.operationForm = {
              ...this.operationForm,
              controlRatio: data.strategyCx
            }

            // this.operationForm.controlRatio = data.strategyCx
            //汇总人数预警
            this.warningStatus()
          }
        })
      },
      //格式化设备数据
      convertDeviceData(data){
        const deviceData = []
        const deviceTime = [];
        const beginTime = data[0].beginTime;
        const endTime = data[0].endTime;
        data.forEach((item,index) => {
          if(beginTime>endTime){
            //晚班
            for(let i = beginTime,j=0; i< 24; i++,j++){
              item[i] = item.tableData[j];
              //获取设备时间
              if(index === 0){
                deviceTime.push(i)
              }
            }
            for(let i = 0,j=0; i< endTime; i++,j++){
              item[i] = item.tableData[j];
              //获取设备时间
              if(index === 0){
                deviceTime.push(i)
              }
            }
          }else {
            for(let i = beginTime,j=0; i<= endTime; i++,j++){
              item[i] = item.tableData[j];
              //获取设备时间
              if(index === 0){
                deviceTime.push(i)
              }
            }
          }
          deviceData.push(item)
        });
        this.deviceTime = deviceTime;
        return deviceData;
      },
      //编辑方案请求
      updateOperationalInfo(params){
        this.loading = true;
        updateOperationalInfo(params).then(response => {
          // console.log(response);
          if(response.code === 200){
            this.$router.replace({path:"/operationManagement/need/list"});
          }
          this.loading = false;
        });
      },
      //取消
      onCancel(){
        this.$router.replace({path:"/operationManagement/need/list"});
      },
      submitStatusForm: function(){
        this.$refs["statusForm"].validate(valid => {
          if (valid) {
            // console.log(valid,this.statusForm);
            const { status } = this.statusForm;
            const { row, column, $index } = this.statusData;
            this.deviceData[$index][column.property] = status;
            this.statusOpen = false;
            this.reset();
          }
        });
      },
      //保存
      onSubmit: function(){
        this.$refs["operationForm"].validate(valid => {
          if (valid) {
            // console.log(valid,this.operationForm, this.fileList);

            //处理附件
            const urls = [];
            this.fileList.forEach(item=>{
              if(item.fileName){
                urls.push(item.fileName)
              }else if(item.status ==="success"){
                urls.push(item.response.fileName)
              }
            })

            //区域汇总
            const number = this.getAreaSum();
            if(this.staffData.length === 0){
              this.msgError('请添加区域')
            }else if(number === 0){
              this.msgError('请填写区域汇总人数')
            }else {
              //处理时间
              const formData = this.operationForm;
              const workTime = parseTime(formData.workTime)
              // const fillingTime = parseTime(formData.fillingTime)

              //编辑需求单id
              const id = this.baseData.id;


              // const params = { ...this.operationForm,deps:this.staffData,workTime,fillingTime,urls,bequeath:formData.bequeath*1,id};
              const params = { ...this.operationForm,deps:this.staffData,workTime,urls,bequeath:formData.bequeath*1,id};
              //根据组别id获取组别名称
              this.depsData.forEach(item=>{
                if(item.workGroupId === formData.workGroupId){
                  params.workGroupName = item.workGroupName
                }
              });
              //根据班次id获取班次名称
              params.shiftTimeId = formData.timeShiftId;
              this.timeShift.forEach(item=>{
                if(item.timeShiftId === formData.timeShiftId){
                  params.timeShiftName = item.timeShiftName
                  params.shiftTimeName = item.timeShiftName
                }
              });


              console.log(params);
              //保存请求
              this.updateOperationalInfo(params)
            }
          }
        })
      },
      classGroup(name){  //根据组别名称获取组别数量
        return this.staffData.filter(o => o.groupName == name).length;
      },
      classArea(name){  //根据区域名称获取区域数量
        return this.staffData.filter(o => o.regionName == name).length;
      },
      classGroupLen(name){  //根据组别名称获取该区域第一个岗位的偏移位置
        const tmp = Array.from(this.groupNum);
        const index = tmp.indexOf(name);  //某岗位在全区域中的偏移位置
        let len = 0;
        for (let i = 0;i < index;i++){
          len += this.classGroup(tmp[i]);
        }
        return len;
      },
      classAreaLen(name){  //根据组别名称获取该区域第一个岗位的偏移位置
        const tmp = Array.from(this.areaNum);
        const index = tmp.indexOf(name);  //某岗位在全区域中的偏移位置
        let len = 0;
        for (let i = 0;i < index;i++){
          len += this.classArea(tmp[i]);
        }
        return len;
      },
      handleChange(e,data){
        // 组别人数变动

        // console.log(tmp,quota)
        const len = this.classAreaLen(data.regionName);
        this.staffData[len].regionNumber = e;

        const { predictNumber, standardNumber, businessClassification } = this.operationForm;

        //预警状态
        this.warningStatus()
        //区域人数合计
        const number = this.getAreaSum()
        this.operationForm.estimatedLaborNum = number;

        if( predictNumber && businessClassification){
          const decide = standardNumber / businessClassification * predictNumber;
          console.log(decide,predictNumber)
          const estimatedArrivalRatio = decide ? (number - decide) / decide *100 : 0;
          this.operationForm.estimatedArrivalRatio = (estimatedArrivalRatio).toFixed(2);
        }else {
          this.operationForm.estimatedArrivalRatio = undefined
        }

        //预估人效比
        const estimateRatio = number&&predictNumber ? predictNumber/number : 0;
        //标准人数上限
        const estimatedArrivalRatio = standardNumber ? (number - standardNumber)/standardNumber : 0;
        this.operationForm.estimateRatio = (estimateRatio*100).toFixed(2);
        this.operationForm.estimatedArrivalRatio = (estimatedArrivalRatio*100).toFixed(2);
      },
      //区域人数合计
      getAreaSum(){
        let number = 0;
        this.staffData.forEach(item => {
          if(item.regionNumber){
            number += item.regionNumber;
          }
        });
        return number
      },
      //定额合计
      getQuotaSum(){
        let number = 0;
        this.staffData.forEach(item => {
          if(item.quota){
            number += item.quota;
          }
        });
        return number
      },
      //获取汇总数据
      getSummaries(param) {
        const {columns, data} = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '汇总人数';
            return;
          }
          const needSum = ["groupNumber","quota","regionNumber"];
          if(needSum.indexOf(column.property) === -1){
            //不需要计算汇总
            return false
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          } else {
            sums[index] = 'N/A';
          }
        });
        return sums;
      },
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        // console.log(row,column,rowIndex,columnIndex)
        if (columnIndex === 0 || columnIndex === 4 || columnIndex === 5 ) {
          //判断区域rowspan数量
          const len = this.classArea(row.regionName);
          const lenName = this.classAreaLen(row.regionName);
          if (rowIndex === lenName) {   //某区域首位岗位
            return {
              rowspan:len,
              colspan:1
            }
          } else return {   //某区域非首位岗位
            rowspan: 0,
            colspan: 0
          };
        }else if(columnIndex === 1 || columnIndex === 2 ){
          //判断区域rowspan数量
          const len = this.classGroup(row.groupName);
          const lenName = this.classGroupLen(row.groupName);
          if (rowIndex === lenName) {   //某班级首位学生行
            return {
              rowspan:len,
              colspan:1
            }
          } else return {   //某班级非首位学生行
            rowspan: 0,
            colspan: 0
          };
        }
      }
    }
  }
</script>

<style>
  .device-wrap .el-table td{
    padding: 0;
  }
  .device-wrap .el-table td .cell{
    padding: 0;
  }
  .device-wrap .el-table td:first-child .cell{
    padding-left: 10px;
  }
</style>
<style scoped>
  .device-wrap .device-head{
    border-bottom: 1px solid #ccc;
  }
  .device-wrap .el-table td .status{
    min-height: 36px;
    box-sizing: border-box;
  }
  .device-wrap .el-table td .status{
    background-color: white;
  }
  .device-wrap .el-table td .status.green{
    background-color: green;
  }
  .device-wrap .el-table td .status.red{
    background-color: red;
  }

  .device-wrap .itemStatus{
    padding-left: 40px;
    display: inline-block;
    line-height: 30px;
    position: relative;
    margin-right: 10px;
  }
  .device-wrap .itemStatus::before{
    content: "";
    display: inline-block;
    width: 35px;
    height: 20px;
    position: absolute;
    left: 0;
    top: 5px;
    background-color: green;
  }
  .device-wrap .itemStatus.red::before{
    background-color: red;
  }
</style>
